package com.mes.web.controller.zc;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.google.gson.Gson;
import com.mes.entity.hy.Product;
import com.mes.entity.tdd.Staff;
import com.mes.entity.zc.CustomerDetails;
import com.mes.entity.zc.Queryzc;
import com.mes.service.zc.CustomerService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;
/**
 * 客户的增删改查
 * @author zc
 *	
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
	@Resource
	private CustomerService service;
	
	/**
	 * 添加客户
	 * @param customerDetails
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/createCustomer")
	public void createCustomer(CustomerDetails customerDetails,HttpServletResponse response,HttpServletRequest request) throws IOException{
		//添加前判断是否已经存在
		int affact=0;
		customerDetails.setEnterDate(new Date());
		//从session中取出用户身份信息
		HttpSession session  = request.getSession();
	    Staff userSession = (Staff) session.getAttribute("staff");
	    if(userSession!=null){
		    String enter = userSession.getStaffname();
			customerDetails.setEnter(enter);
	    }else{
	    	customerDetails.setEnter("游客");
	    }
		System.out.println(customerDetails.getName());
		int count = service.selectCustomerByName(customerDetails.getName());
		if(count>0){
			affact=2;
		}else{
			affact=service.createCustomer(customerDetails);
		}
		response.getWriter().print(affact);
	}
	/**
	 * 查询客户列表，分页，条件
	 * @param queryzc
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/selectAllCustomer")
	public void selectAllCustomer(Queryzc queryzc,HttpServletResponse response,HttpServletRequest request) throws Exception{
		//查询客户总数
		if(request.getParameter("limit")!=null && request.getParameter("offset")!=null){
			queryzc.setLimit(Integer.parseInt(request.getParameter("limit")));
			queryzc.setOffset(Integer.parseInt(request.getParameter("offset")));
		}
		int count = service.customerCount(queryzc);
		List<CustomerDetails> customerList = service.selectCustomerDetails(queryzc);
		
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(customerList, jsonConfig);
		jsonObject.put("total", count);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	/**
	 * 删除客户
	 * @param ids
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/deleteCustomer")
	public void deleteCustomer(String ids,HttpServletResponse response) throws IOException {
		//查询要删除的客户是否存在于销售表中
		int num = service.selectOrder(ids);
		if(num>0){//存在？
			int affact = -1;
			response.getWriter().print(affact);
		}else{//不存在？
			int affact = service.deleteCustomer(ids);
			response.getWriter().print(affact);
		}
		
	}
	/**
	 * 导出
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/export")
	public void export(HttpServletResponse response,HttpServletRequest request,Queryzc queryzc) throws UnsupportedEncodingException {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("所有客户信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell((short) 1);
		cell.setCellValue("客户名称");
		cell.setCellStyle(style);
		cell = row.createCell((short) 2);
		cell.setCellValue("客户类型");
		cell.setCellStyle(style);
		cell = row.createCell((short) 3);
		cell.setCellValue("联系人");
		cell.setCellStyle(style);
		cell = row.createCell((short) 4);
		cell.setCellValue("联系电话");
		cell.setCellStyle(style);
		cell = row.createCell((short) 5);
		cell.setCellValue("运送方式");
		cell.setCellStyle(style);
		cell = row.createCell((short) 6);
		cell.setCellValue("结算方式");
		cell.setCellStyle(style);
		cell = row.createCell((short) 7);
		cell.setCellValue("付款周期");
		cell.setCellStyle(style);
		cell = row.createCell((short) 8);
		cell.setCellValue("录入人");
		cell.setCellStyle(style);
		cell = row.createCell((short) 9);
		cell.setCellValue("录入日期");
		cell.setCellStyle(style);
		
		//做判断，是不是导出所有
		List<CustomerDetails> list = new ArrayList<CustomerDetails>();
		if(queryzc.getExportType().equals("1")) {
			//String name = queryzc.getName();
			list = service.selectCustomerDetails(queryzc);// 导出当前页
		}else {
			list = service.selectCustomerAll();// 导出所有
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			CustomerDetails customerDetails = list.get(i);
			System.out.println(sdf.format(customerDetails.getEnterDate()));
			row.createCell((short) 0).setCellValue(i + 1);
			row.createCell((short) 1).setCellValue(customerDetails.getName());
			row.createCell((short) 2).setCellValue(customerDetails.getType());
			row.createCell((short) 3).setCellValue(customerDetails.getLinkman());
			row.createCell((short) 4).setCellValue(customerDetails.getPhone());
			row.createCell((short) 5).setCellValue(customerDetails.getDelivery());
			row.createCell((short) 6).setCellValue(customerDetails.getPayments());
			row.createCell((short) 7).setCellValue(customerDetails.getPaydate());
			row.createCell((short) 8).setCellValue(customerDetails.getEnter());
			row.createCell((short) 9).setCellValue(sdf1.format(customerDetails.getEnterDate()));
		}
		
		String nowtime = sdf.format(now);
		String fileName = nowtime + "客户信息表.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	/**
	 * 根据id查询客户
	 * @throws Exception 
	 */
	@RequestMapping("/toEditCustomer")
	public void toEditCustomer(long id,HttpServletResponse response) throws Exception {
		CustomerDetails customerDetails = service.selectCustomerByid(id);
		Gson gson = new Gson();
	    String json = gson.toJson(customerDetails);
	    ResponseUtil.write(response, json);
	}
	
	/**
	 * 修改客户信息
	 * @throws IOException 
	 */
	@RequestMapping("/editCustomer")
	public void editCarRoom(CustomerDetails customerDetails ,HttpServletResponse response,HttpServletRequest request) throws IOException {
		customerDetails.setEnterDate(new Date());
		//从session中取出用户身份信息
		HttpSession session  = request.getSession();
	    Staff userSession = (Staff) session.getAttribute("staff");
	    if(userSession!=null){
		    String enter = userSession.getStaffname();
			customerDetails.setEnter(enter);
	    }else{
	    	customerDetails.setEnter("游客");
	    }
		//修改前判断是否已存在
		int affact = 0;
			affact = service.editCustomer(customerDetails);
		response.getWriter().print(affact);
	}
	
	// 导入
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws URISyntaxException, IOException {
		String savePath = ((HttpSession) request).getServletContext().getRealPath(
				"/WEB-INF/" + file.getOriginalFilename());
		File newFile = new File(savePath);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		// 取文件后缀
		String subfix = savePath.lastIndexOf(".") == -1 ? "" : savePath
				.substring(savePath.lastIndexOf(".") + 1);
		List<List<String>> lists = new ArrayList<>();
		// 获取导入行数
		List<String> names = names();
		int num = names.size();
		if (subfix.equals("xls")) {
			lists = ExcelUtils.readXls(savePath, request, num+1);
		} else if (subfix.equals("xlsx")) {
			lists = ExcelUtils.readXlsx(savePath, request, num+1);
		} else {
			response.getWriter().print("0");
		}
		int count = 0;
		int flag = 1;
		for (int i = 0; i < lists.size(); i++) {
			List<String> list = new ArrayList<>();
			list = lists.get(i);
			CustomerDetails customerDetails=new CustomerDetails();
			customerDetails.setName(list.get(0) == null ? "" : list.get(0));
			customerDetails.setType(list.get(1) == null ? "" : list.get(1));
			customerDetails.setLinkman(list.get(2) == null ? "" : list.get(2));
			customerDetails.setPhone(list.get(3) == null ? "" : list.get(3));
			customerDetails.setDelivery(list.get(4) == null ? "" : list.get(4));
			customerDetails.setPayments(list.get(5) == null ? "" : list.get(5));
			customerDetails.setPaydate(list.get(6) == null ? "" : list.get(6));
			customerDetails.setEnter(list.get(7) == null ? "" : list.get(7));
			customerDetails.setEnterDate(new Date());
		// 添加功能
		service.createCustomer(customerDetails);
		count++;
		}
		if (count == 0) {
			flag = -1;
		}
		response.getWriter().print(flag);
	}

	// 导入模板表头
	public List<String> names() {
		List<String> list = new ArrayList<>();
		list.add("客户名称");
		list.add("客户类型");
		list.add("联系人");
		list.add("联系电话");
		list.add("运送方式");
		list.add("结算方式");
		list.add("付款周期");
		list.add("录入人");
		return list;
	}
	//导出模板
	@RequestMapping("/doExportFile")
	public void doExportFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ExcelUtils.exportFile("客户信息导入模板",names(), response);
	}
	
	/**
	 * 根据客户名称查个数
	 * @param name
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/selectCustomerByName")
	public void selectCustomerByName(String name,HttpServletResponse response,HttpServletRequest request) throws Exception{
		int count = service.selectCustomerByName(name);
		response.getWriter().print(count);
	}
}
